package com.xywy.wjk;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xywy.R;
import com.xywy.R.id;
import com.xywy.common.BaseActivity;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.sync.SyncWeightScaleData;
import com.xywy.common.util.MD5Util;
import com.xywy.common.widget.MyProgress;
import com.xywy.fwc.net.BaseParser;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.Request;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.bean.WeightData;
import com.xywy.wjk.dao.WeightDataDao;
import com.xywy.wjk.dao.WeightDataDao.Properties;

import de.greenrobot.dao.query.QueryBuilder;

/*****************************************
 * @ClassName: WjkDataInfo
 * @Package com.xywy.wjk
 * @Description: 数据列表
 * @author CodeMonkeyCui
 * @date 2014年11月21日 上午9:11:45
 * @version V1.0
 *******************************************/
public class WjkDataInfo extends BaseActivity implements OnClickListener {
	private final String secret_key = "213aBc$l;@13";

	private ListView mListView;
	private List<WeightData> data;
	private TextView titleName;
	private RelativeLayout rl_wjk_detail_back;
	private TextView rl_wjk_detail_title;
	private WjkDayInfoAdapter adapter;
	private SharedPreferences sp;
	private Editor editor;
	private ImageView iv_noneData;
	private LinearLayout ll_content;
	private MyProgress myProgress;
	private User current_user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.wjl_data_info);
		this.preInit();
		this.initView();
		this.loadData();
	}

	@Override
	public void preInit() {
		// TODO Auto-generated method stub
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
		editor = sp.edit();
		current_user = UserKeeper.getCurrentUser(this);
		initDAO();
	}

	@Override
	public void loadData() {
		// TODO Auto-generated method stub
		Intent intent = getIntent();
		// data = intent.getParcelableArrayListExtra("data");
		data = getData();
		if (data.size() > 0) {
			adapter = new WjkDayInfoAdapter(data, this);
			mListView.setAdapter(adapter);
			mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View v,
						int position, long arg3) {
					// TODO Auto-generated method stub
					showDeleteAlert(v, position);
					return false;
				}
			});
			iv_noneData.setVisibility(View.GONE);
		} else {
			titleName.setVisibility(View.GONE);
			iv_noneData.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void initView() {
		// TODO Auto-generated method stub
		myProgress = new MyProgress(this, 1000);
		mListView = (ListView) findViewById(R.id.lv);
		titleName = (TextView) findViewById(R.id.titleName);
		rl_wjk_detail_back = (RelativeLayout) findViewById(R.id.rl_wjk_detail_back);
		rl_wjk_detail_back.setOnClickListener(this);
		rl_wjk_detail_title = (TextView) findViewById(R.id.rl_wjk_detail_title);
		iv_noneData = (ImageView) findViewById(R.id.iv_noneData);
		ll_content = (LinearLayout) findViewById(R.id.ll_content);
	}

	private WeightDataDao weightDataDao; // 体重秤表dao；

	private void initDAO() {
		BaseDao baseDao = BaseDao.getInstance(WjkDataInfo.this);
		weightDataDao = baseDao.getWeightDataDao();
	}

	private void showDeleteAlert(View v, final int position) {
		final Dialog dialog = new Dialog(this, R.style.Translucent_NoTitle);
		dialog.setContentView(R.layout.wjk_delete_menu);
		TextView delete = (TextView) dialog.findViewById(R.id.delete);
		delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				deleteDataInServer(data.get(position),position
						);
				//这个地方  该加的是删除接口
				dialog.dismiss();
				myProgress.start();
			}
		});
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
		int height = mListView.getMeasuredHeight() / data.size();
		// 显示的坐标
		lp.x = v.getWidth() / 2;

		lp.y = v.getTop() + titleName.getBottom();
		dialogWindow.setAttributes(lp);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	private List<WeightData> getData() {
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderDesc(Properties.Date);
		List<WeightData> list = qb.list();
		return list;
	}

	/**
	 * 
	 * @author wangwenlong adapter
	 * 
	 */
	class WjkDayInfoAdapter extends BaseAdapter {
		List<WeightData> data;
		Context context;
		SimpleDateFormat mFormat;
		Calendar calendar = Calendar.getInstance();

		public WjkDayInfoAdapter(List<WeightData> data, Context context) {
			super();
			this.data = data;
			this.context = context;
			mFormat = new SimpleDateFormat("");
		}

		Calendar c = Calendar.getInstance();

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			WeightData entity = data.get(position);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = View.inflate(context, R.layout.wjk_data_item,
						null);
				holder.data = (TextView) convertView.findViewById(R.id.data);
				holder.date = (TextView) convertView.findViewById(R.id.date);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.data.setText(entity.getWeight() + "");
			calendar.setTimeInMillis(entity.getDate());
			int noon = calendar.get(Calendar.AM_PM);
			String str;
			if (noon == 0) {
				str = "上午";
			} else {
				str = "下午";
			}
			DecimalFormat df = new DecimalFormat("00");
			String dateStr = (calendar.get(Calendar.MONTH) + 1) + "月"
					+ calendar.get(Calendar.DAY_OF_MONTH) + "日" + "    " + str
					+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
					+ df.format(calendar.get(Calendar.MINUTE));
			holder.date.setText(dateStr);
			return convertView;
		}

		class ViewHolder {
			public TextView data;
			public TextView date;
		}

	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.rl_wjk_detail_back:
			finish();
			break;

		default:
			break;
		}
	}

	/**
	 * 调用接口删除服务器上数据；
	 */
	private void deleteDataInServer(final WeightData data,final int position) {

		long datatime = data.getDate() / 1000;

		String urlStr = "http://api.yun.xywy.com/index.php/api/setdata/del_data/";
//		String userid = sp.getString("userid", "");
		String userid = UserKeeper.getCurrentUser(this).getUserid();
		String app_username = "xywy_tizhong";
		String sort = "tizhong";
		String app_data = "temp_automactily_device_identify";
		String shou_data = "temp_handly_device_identify";
		// $pwd.$xywy_userid.$sort.$app_data.$shou_data.$datatime.$app_username;
		String sn = secret_key + userid + sort + app_data + shou_data
				+ datatime + app_username;

		HashMap<Object, Object> params = new HashMap<Object, Object>();

		params.put("xywy_userid", userid);
		params.put("app_username", app_username);
		params.put("sort", sort);
		params.put("app_data", app_data);
		params.put("shou_data", shou_data);
		params.put("datatime", datatime);
		try {
			params.put("sn", MD5Util.md5(sn));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Request.postData(new BaseParser<Integer>() {

			@Override
			public Integer parseJson(String result) {
				JSONObject jsonObject;
				int status = -1;
				try {
					jsonObject = new JSONObject(result);
					status = jsonObject.getInt("status");
					return status;
				} catch (JSONException e) {
					e.printStackTrace();
					Message msg = Message.obtain();
						msg.arg1 = -1;
						deleteHandler.sendMessage(msg);
				}
				return status;
			}
		}, new DataCallBack<Integer>() {

			@Override
			public void dataCall(Integer t) {
				Message msg = Message.obtain();
				if(t == null){
					msg.arg1 = -1;
					deleteHandler.sendMessage(msg);
					return;
				}
				msg.arg1 = t;
				msg.obj = data;
				msg.arg2 = position;
				switch (t) {
				case 0:
					// TODO: 已经正确删除服务器信息，；执行后续操作
					break;
				case -1:
					// TODO: 解析异常；
					
					break;
				default:
					break;
				}
				deleteHandler.sendMessage(msg);

			}
		}, urlStr, params);

	}
	
	private Handler deleteHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			myProgress.stop();
			switch (msg.arg1) {
			case 0:
				Toast.makeText(WjkDataInfo.this, "删除成功", Toast.LENGTH_SHORT).show();
			    int position = msg.arg2;
				weightDataDao.delete(data.get(position));
				data.remove(data.get(position));
				if(data.size() ==0){
					titleName.setVisibility(View.GONE);
					iv_noneData.setVisibility(View.VISIBLE);
				}
				adapter.notifyDataSetChanged();
				break;
			case -1:
				Toast.makeText(WjkDataInfo.this, "您的网络不好,删除失败", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		};
	};
}
